RDB への書き込み
実例
単一 ContactInfo を挿入する writeContact の実装
code:fsharp
type CustomerId = CustomerId of int
type String50 = String50 of string
type Birthdate = Birthdate of DateTime
type Customer =
{ CustomerId: CustomerId
Name: String50
Birthdate: Birthdate }
1. すべてのテーブルの型を定義
code:fsharp
type Db = SqlProgrammabilityProvider<connectionString>
2. writeContact の実装
code:fsharp
let writeContact (productionConnection: SqlConnection) (Contact contact) =
// ドメインオブジェクトからプリミティブ値を抽出
let contactId = contact.ContactId |> ContactId.value
let isEmail, isPhone, emailAddressOpt, phoneNumberOpt =
match contact.Info with
| Email emailAddress ->
let emailAddressString = emailAddress |> EmailAddress.value
true, false, Some emailAddressString, None
| Phone phoneNumber ->
let phoneNumberString = phoneNumber |> PhoneNumber.value
false, true, None, Some phoneNumberString
// 新しい行を作成
let contactInfoTable = new Db.dbo.Tables.ContactInfo()
let newRow = contactInfoTable.NewRow()
newRow.ContactId <- contactId
newRow.isEmail <- isEmail
newRow.isPhone <- isPhone
newRow.EmailAddress <- emailAddressOpt
newRow.PhoneNumber <- phoneNumberOpt
// テーブルに追加
contactInfoTable.Rows.Add newRow
// DB に変更を加える
let recordsAffected = contactInfoTable.Update(productionConnection)
recordsAffected
3. (別案)SQL 文を実行する
code:fsharp
type InsertContact = SqlCommandProvider<"""
INSERT INTO ContactInfo
VALUES (@contactId, @isEmail, @isPhone, @emailAddress, @phoneNumber)
""", connectionString>
let writeContact (productionConnection: SqlConnection) (Contact contact) =
let contactId = contact.ContactId |> ContactId.value
let isEmail, isPhone, emailAddressOpt, phoneNumberOpt =
match contact.Info with
| Email emailAddress ->
let emailAddressString = emailAddress |> EmailAddress.value
true, false, emailAddressString, null
| Phone phoneNumber ->
let phoneNumberString = phoneNumber |> PhoneNumber.value
false, true, null, phoneNumberString
use cmd = new InsertContact(productionConnection)
cmd.Execute(contactId, isEmail, isPhone, emailAddress, phoneNumber)